﻿var me = this;

var vm = this.lookupViewModel();
var ukCrossCharge = ref.UKCrossCharge.getValue();
var controller = this.lookupController();
var store3 = ref.datagrid3.getStore();

//是否扣减
var isDeduction = ['1', '2', '3', '6'].includes(ref.ExpenseType.getValue());
var _company = ref.companyC.getValue();
var year = ref.fiscalYear.getValue().split('_')[0];

if (isDeduction && _company == 'JLRC') {
    controller.budgetControl = controller.budgetControl || {};
    controller.balance = controller.balance || {};
    var isAnswerCall = false;

    if (ref.Resubmit) {
        isAnswerCall = ref.Resubmit.text == 'Answer';
    }
    /*
     重新提交有两种情况.
        1.Enquiry之后的重新提交 解冻有价格差的金额.
        2.Rejcect之后的重新提交 冻结金额.
       
        所以这里要判断重新提交是Enquiry之后还是 Reject之后.
        通过ref.Resubmit.text来判断.
        (注意:Resubmit按钮不是每次都会从出现.要判断)
     */

    if (isAnswerCall) {
        var process = function (record) {
            var budgetitemId = ref.BudgetItems.getValue();
            var pa = record.get('ProjectActivity');
            var paList = vm.get('NebulogyForm.ProjectActivityList');
            var paId = paList.filter((r) => { return r.ProjectActivity == pa })[0].ID;

            var priceDiffer = record.get('PriceDiffer') || 0;
            var caFilterData = store3.data.items.filter(function (rr) {
                return rr.get('DescriptionOfSuppliesServices') == record.get('DescriptionOfSuppliesServices') && rr.get('ProjectActivity') == record.get('ProjectActivity') && rr.get('Company') == 'JLRC';
            });
            var cost = 0;
            if (caFilterData.length) {
                var currentData = caFilterData[0];

                priceDiffer = (priceDiffer * currentData.get('CompanySharingRatio')) / 100;
                cost = currentData.get('Cost');
            }
            controller.getBalance(pa);
            if (controller.budgetControl[pa] == 'Y') {
                Ext.PAIRest.request({
                    ns: PAI.application.serviceUrl,
                    url: 'jlr-rest/api/budgetFmebugetItem/updateFreezingAmount',
                    method: "POST",
                    async: false,
                    data: {
                        budgetitemId: budgetitemId,
                        freezeOrUnfreeze: 1,
                        projectActivityId: paId,
                        thawAmount: priceDiffer,
                        formCost: cost,
                        company: 'JLRC',
                        folio: vm.get('NebulogyForm.formInfo.folio'),
                        actInstId: PAI.Global.getUrlData('destInstId'),
                        actionName: requestData.action,
                        fromBalance: controller.balance[pa],
                        yearVal: year
                    },
                    success: function (data) {
                        console.log('Thaw success');
                    }
                });
            }
        }

        if (ukCrossCharge == 'UKJLRC' || ukCrossCharge == 'No') {
            var expenseType = ref.ExpenseType.getValue();

            var store = expenseType == '4' ? ref.datagrid7.getStore() : ref.datagrid2.getStore();

            Ext.each(store.data.items, function (record) {
                process(record);
            });
        }
    } else {
        //退回发起人 解冻. 重新提交 冻结.
        //1，enquirer
        //点击enquier的时候 不做任何金额处理
        //answer的时候，如果表单不做金额修改，传0 ，做了金额修改 传差值

        //1.解冻  2.冻结

        //2，reject
        //点击reject 释放金额
        //重新提交，如果页面不做金额修改，传页面上面的占用金额
        //如果金额修改，传修改后的金额（也是页面上的占用金额）
        if (requestData.action == 'PA_ReturnOriginator' || requestData.action == 'PA_ReturnOriginatorSelfExBack' || requestData.action == 'Resubmit' || requestData.action == 'PA_RecallNotStarted') {
            //进行冻结/解冻操作
            if (ukCrossCharge == 'UKJLRC' || ukCrossCharge == 'No') {

                Ext.each(store3.data.items, function (record) {
                    var currentData = record.data;
                    var company = currentData.Company;

                    if (currentData.budgetControl == 'Y' && company == 'JLRC') {

                        var pa = currentData.ProjectActivity;

                        var paList = vm.get('NebulogyForm.ProjectActivityList');
                        var paId = paList.filter((r) => { return r.ProjectActivity == pa })[0].ID;

                        var budgetitemId = ref.BudgetItems.getValue();
                        //点Enquiry按钮,传的是0.
                        var cost = requestData.action == 'PA_ReturnOriginatorSelfExBack' ? 0 : currentData.Cost;

                        var freezeOrUnfreeze = 0;

                        switch (requestData.action) {
                            case 'PA_ReturnOriginator':
                            case 'PA_RecallNotStarted':
                                freezeOrUnfreeze = 1;
                                break;
                        }

                        //1 解冻, 0 冻结
                        Ext.PAIRest.request({
                            ns: PAI.application.serviceUrl,
                            url: 'jlr-rest/api/budgetFmebugetItem/updateFreezingAmount',
                            method: "POST",
                            async: false,
                            data: {
                                budgetitemId: budgetitemId,
                                freezeOrUnfreeze: freezeOrUnfreeze,
                                projectActivityId: paId,
                                thawAmount: cost,
                                formCost: cost,
                                company: company,
                                folio: vm.get('NebulogyForm.formInfo.folio'),
                                actInstId: PAI.Global.getUrlData('destInstId'),
                                actionName: requestData.action,
                                fromBalance: currentData.Balance,
                                yearVal: year
                            },
                            success: function (data) { }
                        });
                    }
                });
            }
        }
    }
}
//点击转办的时侯发送邮件通知审批人
if (requestData.action == 'PA_Redirect') {
    var sn = PAI.Global.getUrlData("sn");
    var k2ProcInstId = 0;
    var activityName = vm.get('NebulogyForm.activityName');
    if (sn != undefined) {
        k2ProcInstId = sn.split('_')[0];
    }
    var sendEmail = {
        //获取转办人信息
        getEmpEmail: () => {
            var EmpList = new Object();
            Ext.PAIRest.request({
                url: 'last/employeeObj/customQuery',
                method: "POST",
                async: false,
                data: {
                    "fields": [
                        { "name": "email" },
                        { "name": "employeeNo" }
                    ],
                    "filter": "id='" + requestData.participants + "'"
                },
                success: function (data) {
                    if (data.data.length > 0) {
                        EmpList = data.data;
                    }
                },
                failure: function (errorData) {
                    console.log('send email error:' + errorData);
                }
            });
            return EmpList;
        },
        //发送邮件
        ApporveEmail: (obj) => {
            Ext.PAIRest.request({
                ns: PAI.application.userServerUrl,
                url: 'email/approval',
                method: 'POST',
                async: false,
                data: {
                    "sn": sn,
                    "k2Account": obj[0].employeeNo,
                    "formDataId": requestData.bizModel.bizModelId,
                    "activityName": activityName,
                    "emailModelId": "db4a4f32-59dc-4b5f-995d-8975e460b2e6",
                    "k2ProcInstId": k2ProcInstId,
                    "approvalEmail": obj[0].email,
                    "noEnableAction": true
                },
                success: function (data) {
                    console.log(data);
                },
                failure: function (errorData) {
                    console.log('send email error:' + errorData);
                }
            });
        }
    };
    var EmpList = sendEmail.getEmpEmail();
    sendEmail.ApporveEmail(EmpList);
} else if (requestData.action == 'Resubmit') {

    var store = ref.ExpenseType.getValue() == '4' ? ref.datagrid7.getStore() : ref.datagrid2.getStore();
    var arr = [];

    var paList = vm.get('NebulogyForm.ProjectActivityList');

    Ext.each(store.data.items, function (record) {

        var paItem = paList.filter(function (data) {
            return data.ProjectActivity == record.get('ProjectActivity');
        });

        if (paItem.length) {
            arr.push(paItem[0].ID);
        }
    });

    Ext.PAIRest.request({
        ns: PAI.application.serviceUrl,
        url: 'jlr-rest/api/budgetFmebugetItem/updateLockStatus',
        method: "PUT",
        async: false,
        data: {
            "paIds": arr.join(','),
            "biId": ref.BudgetItems.getValue()
        },
        success: function (data) { },
        failure: function (jsondata) { }
    });
}

